<!--
  * 云喇叭表单
-->
<template>
  <a-modal :title="formData.id ? '修改' : '新增'" :width="1000" :open="visibleFlag" @cancel="onClose" :maskClosable="false" :destroyOnClose="true">
    <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical" :disabled="props.formType == 'view'">
      <a-row :gutter="16">
        <a-col :span="24">
          <group-title :iconOptions="{ class: 'text-blue-400' }">基础信息</group-title>
        </a-col>
        <a-col :span="12">
          <a-form-item label="设备厂商" name="manufacturerId">
            <CustomSelect
              v-model:value="formData.manufacturerId"
              :placeholder="'请选择设备厂商'"
              queryParamKey="manufacturerName"
              :api="manufacturerApi.page"
              :initParams="{ manufacturerId: formData.manufacturerId }"
              @change="(...data) => handleChange(data)"
              label-field="manufacturerName,id"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="formData.manufacturerId">
          <a-form-item label="产品型号" name="deviceModelId">
            <CustomSelect
              v-model:value="formData.deviceModelId"
              :placeholder="'请选择产品型号'"
              queryParamKey="deviceModelName"
              :api="deviceModelApi.page"
              :queryParams="{
                manufacturerId: formData.manufacturerId,
                deviceType: cloudDevice,
              }"
              :initParams="{ deviceModelId: formData.deviceModelId }"
              @change="(...data) => handleChangedeviceModel(data)"
              label-field="deviceModelName,id"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="props.formType == 'view'">
          <a-form-item label=" 设备类型" name="deviceType">
            <a-select v-model:value="formData.deviceType" allowClear :options="DEVICE_TYPE" placeholder="请选择设备类型" />
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="props.formType == 'view'">
          <a-form-item label=" 设备状态" name="status">
            <a-select v-model:value="formData.status" allowClear :options="DEVICE_STATUS" placeholder="请选择设备类型" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <group-title :iconOptions="{ class: 'text-blue-400' }">设备信息</group-title>
        </a-col>
        <a-col :span="24">
          <a-form-item label="设备SN" name="sn">
            <a-input v-model:value="formData.sn" placeholder="请输入设备SN" />
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="props.formType == 'view'">
          <a-form-item label="设备编号" name="id">
            <a-input v-model:value="formData.id" placeholder="请输入设备编号" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <a-row :gutter="16" v-if="props.formType == 'view'">
      <a-col :span="24">
        <group-title :iconOptions="{ class: 'text-blue-400' }">当前绑定信息</group-title>
      </a-col>
      <a-col :span="12"> 商户名称：{{ formData.merchantName }} </a-col>
      <a-col :span="12"> 门店名称：{{ formData.storeName }} </a-col>
    </a-row>
    <a-row :gutter="16" v-if="props.formType == 'view'" class="m-t-4">
      <a-col :span="24">
        <group-title :iconOptions="{ class: 'text-blue-400' }">绑定记录</group-title>
      </a-col>
      <a-col :span="24">
        <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :loading="tableLoading" :pagination="false" />
      </a-col>
    </a-row>
    <template #footer>
      <a-space v-if="props.formType != 'view'">
        <slot></slot>
        <a-button @click="onReset" type="link">重置</a-button>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="testRow">验证</a-button>
      </a-space>
    </template>
  </a-modal>
  <CloudTestForm v-model:open="testOptions.open" :formType="testOptions.type" :rowData="testOptions.data">
    <a-button type="primary" @click="onSubmit">保存</a-button>
  </CloudTestForm>
</template>
<script setup>
  import { reactive, ref, nextTick, computed, watch } from 'vue'
  import _ from 'lodash'
  import { message } from 'ant-design-vue'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import { smartSentry } from '/@/lib/smart-sentry'
  import CustomSelect from '/@/components/business/comment/CustomSelect.vue'
  import { strToArr, selectDictLabel } from '/@/utils/common'
  import { manufacturerApi } from '/@/api/business/b-operation/manufacturer/index'
  import { deviceModelApi } from '/@/api/business/b-operation/device-model/index'
  import { deviceApi } from '/@/api/business/b-operation/device'
  import { deviceLogApi } from '/@/api/business/b-operation/device/device-log'
  import { DEVICE_TYPE, DEVICE_STATUS } from '/@/constants/dict'
  import { useRoute } from 'vue-router'
  import CloudTestForm from './cloud-test-form.vue'
  const route = useRoute()
  // ---------------------------- 表格列 ----------------------------
  const cloudDevice = computed(() => {
    // 0云喇叭 1云打印
    return route.path.includes('cloud-speaker') ? 0 : 1
  })

  const props = defineProps({
    open: {
      type: Boolean,
      default: false,
    },
    // 表单类型 add/update/view
    // add: 新增, update: 编辑,view: 查看
    formType: {
      type: String,
      default: 'add',
    },
    rowData: {
      type: Object,
      default: () => {},
    },
  })
  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['ok', 'update:open'])
  const visibleFlag = computed({ get: () => props.open, set: (val) => emits('update:open', val) })

  const columns = ref([
    {
      title: '时间',
      dataIndex: 'cTime',
      ellipsis: true,
    },
    {
      title: '绑定对象',
      dataIndex: 'merchantName',
      customRender: (column) => {
        return `${column.text}(${column.record.no})`
      },
      ellipsis: true,
    },
  ])
  const tableData = ref([])
  const tableLoading = ref(false)

  const getDeviceLogList = async () => {
    tableLoading.value = true
    let queryParams = {
      pageSize: 100,
      pageNo: 1,
      deviceId: props.rowData.id,
      sortFields: [
        {
          field: 'c_time',
          order: 'desc',
        },
      ],
    }
    try {
      let queryResult = await deviceLogApi.page(queryParams)
      tableData.value = queryResult.data
    } catch (e) {
      smartSentry.captureError(e)
    } finally {
      tableLoading.value = false
    }
  }

  function onReset() {
    Object.assign(formData.value, formDefault)
    nextTick(() => {
      formRef.value?.clearValidate()
    })
  }
  // ------------------------ 显示与隐藏 ------------------------
  function onClose() {
    Object.assign(formData.value, formDefault)
    visibleFlag.value = false
    nextTick(() => {
      formRef.value?.clearValidate()
    })
  }

  // ------------------------ 获取表单数据 ------------------------
  async function getFormData(data) {
    SmartLoading.show()
    try {
      let res = await deviceApi.findId(data)
      formData.value = { ...res.data }
    } catch (err) {
      smartSentry.captureError(err)
    } finally {
      SmartLoading.hide()
    }
  }
  /* 切换厂商 */
  function handleChange(data) {
    formData.value.dmId = undefined
    formData.value.deviceModelId = undefined
    if (!data?.[1][0]) {
      formData.value.manufacturerName = undefined
      return
    }
    formData.value.manufacturerName = data[1][0].manufacturerName
  }
  /* 切换产品型号 */
  function handleChangedeviceModel(data) {
    if (!data?.[1][0]) {
      formData.value.deviceModelName = undefined
      return
    }
    formData.value.deviceModelName = data[1][0].deviceModelName
  }

  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref()

  const formDefault = {
    deviceType: undefined, //设备类型 0云喇叭 1云打印
    oAgentName: undefined, //所属服务商名称
    manufacturerName: undefined, //厂商名称
    deviceModelName: undefined, //产品型号名称
    manufacturerId: undefined, //厂商编码
    cTime: undefined, //创建时间
    dmId: undefined, //设备模版编号
    storeId: undefined, //门店编号
    oAgentId: undefined, //所属服务商编号
    merchantName: undefined, //商户名称
    cUserId: undefined, //创建用户编号
    oUserType: undefined, //所属用户类型
    uUserId: undefined, //更新用户编号
    isOpen: undefined, //是否启用 0否 1是
    merchantId: undefined, //商户编号
    cUserName: undefined, //创建人
    oUserId: undefined, //所属用户编号
    uUserName: undefined, //更新人
    deviceModelId: undefined, //产品型号编号
    storeName: undefined, //门店名称
    uTime: undefined, //更新时间
    id: undefined, //编号
    sn: undefined, //sn编码
    status: undefined, //状态 0未激活 1正常
  }

  let formData = ref({ ...formDefault })

  const rules = {
    manufacturerId: [{ required: true, message: '设备厂商 必填' }],
    dmId: [{ required: true, message: '设备 必填' }],
    deviceModelId: [{ required: true, message: '产品型号 必填' }],
    sn: [{ required: true, message: '设备SN 必填' }],
  }

  // 点击确定，验证表单
  async function onSubmit() {
    try {
      await formRef.value.validateFields()
      save()
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!')
    }
  }

  // 新建、编辑API
  async function save() {
    SmartLoading.show()
    try {
      let data = { ...formData.value, deviceType: cloudDevice.value }
      if (formData.value.id) {
        await deviceApi.update(data)
      } else {
        await deviceApi.insert(data)
      }
      message.success('操作成功')
      emits('ok')
      onClose()
      testOptions.value.open = false
    } catch (err) {
      smartSentry.captureError(err)
    } finally {
      SmartLoading.hide()
    }
  }

  // 测试设备
  const testOptions = ref({
    open: false,
    data: null,
  })
  const testRow = async () => {
    try {
      await formRef.value.validateFields()
      testOptions.value = { open: true, data: formData.value }
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!')
    }
  }

  watch(
    [() => props.rowData, () => props.open],
    (val) => {
      console.log('formData.value==>', formData.value)

      if (props.open && props.rowData && props.formType != 'add') {
        getFormData(val[0])
        getDeviceLogList()
      }
    },
    { immediate: true },
  )
</script>
